import 'package:safetymonitor/app/components/custom_app_bar.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_divider.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/utils/perm_util.dart';
import 'package:permission_handler/permission_handler.dart';

/// 系统权限管理列表
/// 可以查看以获取的权限和未获取的权限
/// 可以跳转到设置页面申请权限
class PermissionPage extends StatefulWidget {
  const PermissionPage({super.key});

  @override
  State<PermissionPage> createState() => _PermissionPageState();
}

class _PermissionPageState extends State<PermissionPage> {
  static final _permStatus = Map.fromEntries(
      PermUtil.all4App.map((perm) => MapEntry(perm, ValueNotifier(false))));

  @override
  void initState() {
    super.initState();
    _initPermissionStatus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: CustomAppBar(
        titleText: '系统权限',
      ),
      body: ListView(
          children: [
            AppGaps.vGap10,
            ..._permStatus.keys
              .map(_buildPermItem)
              .joinWith(CustomDivider.grey),
          ],
      ),
    );
  }

  /// 获取权限状态
  Future<void> _initPermissionStatus() async {
    for (final perm in _permStatus.keys) {
      final status = await perm.isAvail(autoReq: true);
      _permStatus[perm]!.value = status;
    }
  }

  // 列表页面
  Widget _buildPermItem(Permission perm) {
    return Container(
      color: Colors.white,
      child: ListTile(
        title: Text(perm.name),
        subtitle: ValueListenableBuilder(
          valueListenable: _permStatus[perm]!,
          builder: (_, value, __) {
            return Text(value ? '已授权' : '未授权', style: TextStyles.grey_14);
          },
        ),
        onTap: perm.openSetting,
        trailing: Icon(
          Icons.arrow_forward_ios,
          size: 16,
          color: Colors.grey[500],
        ),
      ),
    );
  }
}
